import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth';
import { readRecords, readUsers, readCategories, writeRecords, generateId } from '@/lib/data';
import { ChallengeRecord } from '@/types';

export async function GET(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value || '';
    const decoded = verifyToken(token);

    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '无权限' },
        { status: 403 }
      );
    }

    const records = readRecords();
    const users = readUsers();
    const categories = readCategories();

    const getCategoryPath = (categoryId: string) => {
      const cat = categories.find(c => c.id === categoryId);
      return cat ? cat.path : categoryId;
    };

    const enriched = records
      .slice()
      .sort((a, b) => (b.createdAt > a.createdAt ? 1 : -1))
      .map(r => {
        const user = users.find(u => u.id === r.userId);
        return {
          id: r.id,
          userId: r.userId,
          username: user?.username || r.userId,
          categoryId: r.categoryId,
          categoryPath: getCategoryPath(r.categoryId),
          score: r.score,
          timeSpent: r.timeSpent,
          points: r.points,
          createdAt: r.createdAt,
        };
      });

    return NextResponse.json({ success: true, records: enriched });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '获取失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value || '';
    const decoded = verifyToken(token);

    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '无权限' },
        { status: 403 }
      );
    }

    // 支持两种方式：
    // 1) 查询参数 id=xxx 单删
    // 2) 请求体 { ids: string[] } 批量删
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

    let ids: string[] = [];
    if (id) {
      ids = [id];
    } else {
      try {
        const body = await request.json();
        ids = Array.isArray(body?.ids) ? body.ids.filter((x: any) => typeof x === 'string') : [];
      } catch {
        // ignore
      }
    }

    if (!ids.length) {
      return NextResponse.json(
        { success: false, message: '缺少要删除的记录ID' },
        { status: 400 }
      );
    }

    const before = readRecords();
    const idSet = new Set(ids);
    const after = before.filter(r => !idSet.has(r.id));
    writeRecords(after);

    return NextResponse.json({ success: true, deleted: before.length - after.length });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '删除失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value || '';
    const decoded = verifyToken(token);

    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '无权限' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { username, categoryPath, score, timeSpent, points, createdAt } = body;

    // 验证必填字段
    if (!username || !categoryPath || score === undefined || timeSpent === undefined) {
      return NextResponse.json(
        { success: false, message: '缺少必要字段：用户名、分类路径、得分、耗时' },
        { status: 400 }
      );
    }

    // 查找用户
    const users = readUsers();
    const user = users.find(u => u.username === username);
    if (!user) {
      return NextResponse.json(
        { success: false, message: `用户 "${username}" 不存在` },
        { status: 400 }
      );
    }

    // 查找分类（categories是扁平数组，直接查找）
    const categories = readCategories();
    const category = categories.find(c => c.path === categoryPath);
    if (!category) {
      return NextResponse.json(
        { success: false, message: `分类路径 "${categoryPath}" 不存在` },
        { status: 400 }
      );
    }

    // 验证数值
    const scoreNum = parseInt(String(score), 10);
    const timeSpentNum = parseInt(String(timeSpent), 10);
    if (isNaN(scoreNum) || isNaN(timeSpentNum) || scoreNum < 0 || timeSpentNum < 0) {
      return NextResponse.json(
        { success: false, message: '得分和耗时必须是有效的非负整数' },
        { status: 400 }
      );
    }

    // 计算积分（如果未提供）
    const pointsNum = points !== undefined ? parseInt(String(points), 10) : (scoreNum * 100 - timeSpentNum);
    const finalPoints = isNaN(pointsNum) ? Math.max(0, scoreNum * 100 - timeSpentNum) : Math.max(0, pointsNum);

    // 创建记录
    const record: ChallengeRecord = {
      id: generateId(),
      userId: user.id,
      categoryId: category.id,
      questions: [], // 导入的记录没有题目详情
      score: scoreNum,
      timeSpent: timeSpentNum,
      points: finalPoints,
      createdAt: createdAt ? new Date(createdAt).toISOString() : new Date().toISOString(),
    };

    const records = readRecords();
    records.push(record);
    writeRecords(records);

    return NextResponse.json({ success: true, record });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '创建记录失败' },
      { status: 500 }
    );
  }
}


